package wechat

import (
	"encoding/json"
	"log"

	"github.com/silenceper/wechat/v2/miniprogram/auth"
)

type WxSession struct {
	OpenID     string `json:"openid"`      // 用户唯一标识
	SessionKey string `json:"session_key"` // 会话密钥
	UnionID    string `json:"unionid"`     // 用户在开放平台的唯一标识符，在满足UnionID下发条件的情况下会返回
}

func ToSession(e interface{}) *WxSession {
	s, ok := e.(string)
	if ok {
		return stringToWxSession(s)
	}

	res, ok := e.(auth.ResCode2Session)
	if ok {
		return toWxSession(res)
	}
	log.Printf("e is %+v, cannot parse", e)
	return nil
}

func toWxSession(res auth.ResCode2Session) *WxSession {
	return &WxSession{
		OpenID:     res.OpenID,
		SessionKey: res.SessionKey,
		UnionID:    res.UnionID,
	}
}

func stringToWxSession(s string) (res *WxSession) {
	err := json.Unmarshal([]byte(s), &res)
	if err != nil {
		log.Printf("stringToWxSession fail, json.Unmarshal err: %+v", err)
		return nil
	}
	return res
}

func (session *WxSession) ToString() string {
	j, err := json.Marshal(session)
	if err != nil {
		log.Printf("wxSession.ToString fail, json.Marshal err: %+v", err)
	}
	return string(j)
}
